#include "serial.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>

using namespace std;



Serial::Serial(char* serial)
{     
  connectStatus = ftdiInit(serial);
}

Serial::~Serial()
{
  ftdiClose();
}

int Serial::ftdiClose()
{
  int ret;
  if ((ret = ftdi_usb_close(&ftdic)) < 0)
  {
    fprintf(stderr, "unable to close ftdi device: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
    return EXIT_FAILURE;
  }
	
  ftdi_deinit(&ftdic);
	
  return EXIT_SUCCESS;
}

int Serial::writeData(unsigned char* writeBuff, int length)
{
  ftdi_usb_purge_rx_buffer(&ftdic);
  ftdi_usb_purge_tx_buffer(&ftdic);
  
  if (connectStatus != EXIT_FAILURE)
  {
    ftdi_write_data(&ftdic, writeBuff, length);
    return 0;
  }
  else
    return -1;
}

int Serial::readData(unsigned char* readBuff, int length)
{
  if (connectStatus != EXIT_FAILURE)
    return ftdi_read_data(&ftdic, readBuff, length);
  else
    return -1;
}

int Serial::ftdiInit(char* serial)
{
  int ret;
  if (ftdi_init(&ftdic) < 0)
  {
    fprintf(stderr, "ftdi_init failed\n");
    return EXIT_FAILURE;
  }
  
  if ((ret = ftdi_usb_open_desc(&ftdic, 0x0403, 0x6001, NULL, serial)) < 0)
  {
    fprintf(stderr, "unable to open ftdi device: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
    return EXIT_FAILURE;
  }
  /*if ((ret = ftdi_usb_open_desc(&ftdic, 0x0403,0x6001,NULL,"08-15")) < 0)
  {
    fprintf(stderr, "unable to open ftdi device: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
    return EXIT_FAILURE;
  }*/
  
  // Initialize everything:
  ftdi_usb_reset(&ftdic);
  if(ftdi_set_line_property(&ftdic, BITS_8, STOP_BIT_1, NONE) < 0)
    fprintf(stderr, "Error setting line property");
  if(ftdi_setflowctrl(&ftdic, SIO_DISABLE_FLOW_CTRL)< 0)
    fprintf(stderr, "Error setting flow control");
  if(ftdi_set_baudrate(&ftdic, 115200) < 0)
    fprintf(stderr, "Error setting baud rate");
  ftdi_usb_purge_rx_buffer(&ftdic);
  ftdi_usb_purge_tx_buffer(&ftdic);
  
  return EXIT_SUCCESS;
}
